<template>
  <div>
    <!-- 规格及价格 -->
    <el-form inline>
      <el-form-item
        v-for="item in labelList"
        :key="item.id"
        :label="item.specsName"
      >
        <el-select
          v-model="item.selected"
          multiple
          filterable
          :placeholder="`请选择${item.specsName}`"
          collapse-tags
          collapse-tags-tooltip
          :max-collapse-tags="2"
          clearable
          class="w-[13rem]"
        >
          <el-option
            v-for="option in item.list"
            :key="option.id"
            :label="option.specsValueName"
            :value="option.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item v-if="labelList?.length > 0">
        <el-button type="primary" @click="getList()" icon="Search">
          搜索
        </el-button>
        <el-button @click="resetBtn" icon="Refresh"> 重置 </el-button>
      </el-form-item>
    </el-form>

    <div class="w-full flex justify-end items-center mb-2">
      <el-button icon="Plus" type="primary" @click="openDrawer(0)">
        新增规格
      </el-button>
    </div>
    <el-table
      :data="tableData"
      style="width: 100%; height: calc(100vh - 17rem)"
      border
    >
      <el-table-column
        v-for="item in labelList"
        :key="item.id"
        :label="item.specsName"
        :prop="item.specsName"
      />

      <el-table-column label="价格(元)" prop="goodsPrice">
        <template #default="{ row }">
          {{ row.goodsPrice ? row.goodsPrice.toFixed(2) : "" }}
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        :min-width="130"
        fixed="right"
      >
        <template #default="{ row }">
          <el-button type="primary" link @click="openDrawer(row.id, row)">
            <el-icon> <Edit /> </el-icon>编辑
          </el-button>
          <el-button type="danger" link @click="handleRemove(row.id)">
            <el-icon>
              <Delete />
            </el-icon>
            删除
          </el-button>
        </template>
      </el-table-column>
      <template #empty>
        <div class="text-center">
          <el-empty description="暂无数据,请先添加规格" />
        </div>
      </template>
    </el-table>

    <PagingQuery
      :page="page"
      :pageSize="pageSize"
      :total="total"
      @getList="getList"
      class="mt-[0.5rem]"
    />

    <el-drawer
      v-model="drawer"
      :title="`${specId == 0 ? '新增' : '编辑'}规格`"
      destroy-on-close
    >
      <InsertUpdateSpec
        ref="insertUpdateSpecRef"
        :detailForm="props.detailForm"
        :spec_detailForm="spec_detailForm"
        :specId="specId"
        :labelList="labelList"
        @handleBack="handleBack"
      />

      <template #footer>
        <el-button @click="drawer = false">取 消</el-button>
        <el-button type="primary" :loading="loading" @click="handleSubmit">
          {{ loading ? "提交中..." : "提 交" }}
        </el-button>
      </template>
    </el-drawer>
  </div>
</template>

<script setup>
import { ref, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { cloneDeep } from "lodash";
import InsertUpdateSpec from "./InsertUpdateSpec.vue";
import PagingQuery from "@/components/PagingQuery.vue";
import { handleApiResponse } from "@/utils/request.js";
import {
  ListGoodsCategorySpecList,
  ListGoodsWithSpecs,
  AddGoodsSpec,
  DeleteGoodsSpec,
} from "../../../../../../wailsjs/go/api/GoodsApi.js";

onMounted(() => {
  selectSpecLabelList();
  getList();
});

const emit = defineEmits(["handleBack"]);
const props = defineProps({
  detailForm: {
    type: Object,
    default: () => ({}),
  },
});

const labelList = ref([]); // 规格列表 搜索条件
async function selectSpecLabelList() {
  handleApiResponse(() =>
    ListGoodsCategorySpecList({
      id: props.detailForm.categoryId,
    })
  ).then((res) => {
    if (res.code == 0) {
      labelList.value = res.data.list || [];
      labelList.value.forEach((item) => {
        item.selected = [];
      });
    }
  });
}

const page = ref(1);
const pageSize = ref(10);
const total = ref(0);
const tableData = ref([]);
async function getList(e) {
  if (e) {
    page.value = e.page;
    pageSize.value = e.pageSize;
  }

  let specsList = cloneDeep(labelList.value).filter((item) => {
    if (item.selected?.length > 0) {
      item.list = item.list.filter((item2) => item.selected.includes(item2.id));
      delete item.selected;
      return true;
    }
  });

  handleApiResponse(() =>
    ListGoodsWithSpecs({
      goodsId: props.detailForm.id,
      specsList: specsList,
      page: page.value,
      pageSize: pageSize.value,
    })
  ).then((res) => {
    if (res.code == 0) {
      total.value = res.data.total || 0;

      let list = res.data.list || [];

      tableData.value =
        list.map((item) => {
          let child = {};
          item.specs.forEach((itemChild) => {
            child[itemChild.specsName] = itemChild.specsValueName;
          });
          return {
            id: item.id,
            goodsPrice: item.goodsPrice / 100,
            ...child,
          };
        }) || [];
    }
  });
}

// 重置按钮
const resetBtn = () => {
  labelList.value.forEach((item) => {
    item.selected = [];
  });

  getList();
};

// 新增/编辑规格
const drawer = ref(false);
const loading = ref(false);
const specId = ref(0);
const insertUpdateSpecRef = ref(null);
const spec_detailForm = ref({});
const openDrawer = (id, row) => {
  if (!labelList.value || labelList.value.length == 0) {
    ElMessage.error("请先设置规格信息");
    return;
  }
  if (id != 0) {
    spec_detailForm.value = cloneDeep(row);
  }

  specId.value = id;
  drawer.value = true;
};

const handleSubmit = () => {
  insertUpdateSpecRef.value?.handleSubmit();
};
const handleBack = (val) => {
  if (val == 1) {
    loading.value = true;
    return;
  }
  specId.value = 0;
  drawer.value = false;
  getList();
};

// 删除规格
const handleRemove = (id) => {
  ElMessageBox.confirm(`确定删除该规格吗？`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    handleApiResponse(() =>
      DeleteGoodsSpec({ id: id, goodsId: props.detailForm.id })
    ).then((res) => {
      if (res.code == 0) {
        ElMessage.success("删除成功");
        getList();
      }
    });
  });
};
</script>

<style scoped lang="scss">
</style>